<template>
  <div>
    录音窗口 展示信息 {{ userStore.name }} {{ userStore.age }}
    <button @click="edits">修改名称</button>
    <div>
      <button @click="startRecord">开始录音</button>
      <button @click="pauseRecord">暂停录音</button>
      <button @click="openaudiofile">打开录音文件</button>
    </div>
    <div>
      123
      <el-select v-model="selectedDevice" placeholder="请选择麦克风" @change="switchSpeakers">
        <el-option
          v-for="device in audioDevices"
          :key="device.deviceId"
          :label="device.label"
          :disabled="device.disabled"
          :value="device.deviceId"
        />
      </el-select>
    </div>
  </div>
</template>

<script lang="ts" setup>
// import { cloneDeep } from 'lodash'
import { useUserStore } from '@/pinia/user'
const userStore = useUserStore()
import audioRecorder from '@/utils/recordingSettings'
const selectedDevice = ref('')
// const backupDisplay = ref('')
const audioDevices = ref<any>([])
const flage = ref(false)
const edits = () => {
  flage.value = !flage.value
  userStore.setName(flage.value ? '李四' : '张三')
}
// const init = async () => {
//   audioDevices.value = await audioRecorder.getAudioDevices().then((d) => d.outputs)
//   selectedDevice.value = await audioRecorder.getDefaultMicrophone(0).then((d) => d.deviceId)
//   backupDisplay.value = cloneDeep(selectedDevice.value)
// }
const startRecord = async () => {
  //开始录音
  window.electron.ipcRenderer.invoke('start-record', selectedDevice.value)
  await audioRecorder.startRecording(selectedDevice.value)
}
const pauseRecord = async () => {
  const blob = await audioRecorder.stopRecording()
  console.log('录音已暂停:', blob)
  download(blob)
  // savedLocally(blob)
}
const switchSpeakers = async (deviceId: string) => {
  await window.electron.ipcRenderer.invoke('switch-speakers', deviceId)
  // if (!devices) {
  //   selectedDevice.value = cloneDeep(backupDisplay.value)
  // }else{
  //   backupDisplay.value = cloneDeep(selectedDevice.value)
  // }
}
//本地下载
const download = async (blob) => {
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `recording_${new Date().getTime()}.wav`
  a.click()
  // 释放 URL 对象
  URL.revokeObjectURL(url)
}
// const savedLocally = async (blob) => {
//   const buffer = await blob.arrayBuffer()

//   window.electron.ipcRenderer.send('save-file', buffer, `recording_${new Date().getTime()}.wav`)
// }
//保存录音
const openaudiofile = async () => {}
</script>

<style scoped lang="scss"></style>
